package servlet;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import dao.UserDao;
import dao.daoimpl.UserDaoImpl;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@WebServlet(name="UploadPhotoServlet",urlPatterns = "/UploadPhotoServlet")
public class UploadPhotoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        SmartUpload smu = new SmartUpload();
        User user= (User) request.getSession().getAttribute("user");
        String rootPath = request.getSession().getServletContext().getRealPath("/resources/users/"+user.getAccount()+"/head");
        File filePath=new File(rootPath);
        if(!filePath.exists()){
            filePath.mkdirs();   //创建文件目录
        }
        try {
            smu.initialize(this.getServletConfig(), request, response);
            smu.setCharset("UTF-8");
            smu.setAllowedFilesList("gif,jpg,png,bmp");
            smu.setMaxFileSize(30*1024*1024);
            smu.upload();
            com.jspsmart.upload.File file = smu.getFiles().getFile(0);
            java.io.File realfile = new java.io.File(rootPath+"/"+file.getFileName());
            file.saveAs(realfile.toString());
            String path = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
            user.setHeadPortrait(basePath+"resources/users/"+user.getAccount()+"/head/"+file.getFilePathName());
            UserDao userDao= new UserDaoImpl();
            userDao.update(user);
            request.getSession().setAttribute("user",user);
        } catch (SmartUploadException e) {
            response.getWriter().write("error");
            e.printStackTrace();
        }
    }

}

